<template>
  <div class="listContent">
    <el-form :rules="rules" :label-position="labelPosition" label-width="140px">
      <el-form-item
        label="操作步骤："
        prop="operationStep"
        style="text-align: left"
      >
        <el-button
          class="btn-text-blue"
          size="mini"
          icon="el-icon-plus"
          @click="addRow"
          v-if="!isReadonly"
          >新建</el-button
        >
        <el-button
          class="btn-text-blue"
          size="mini"
          icon="el-icon-download"
          @click="downloadModel"
          v-if="!isReadonly"
          >下载导入模板</el-button
        >
        <el-button
          class="btn-text-blue"
          size="mini"
          icon="el-icon-download"
          @click="derive"
          >导出</el-button
        >

        <el-button
          class="btn-text-blue"
          size="mini"
          icon="el-icon-upload2"
          @click="uploadExcel"
          v-if="!isReadonly"
          >导入</el-button
        >
        <el-button
          class="btn-text-blue"
          size="mini"
          icon="el-icon-document-copy"
          @click="pasteFromExcel"
          v-if="!isReadonly"
          >从excel粘贴</el-button
        >
        <div class="tipTitle" v-html="tipText" v-if="!isReadonly"></div>
        <el-table
          :data="listConfig.listData"
          border
          :cell-style="tableCellStyle"
          style="width: 100%"
          :header-cell-class-name="starAdd"
        >
          <el-table-column
            prop="rowNum"
            label="序号"
            width="100"
            align="center"
          ></el-table-column>

          <el-table-column prop="item" label="操作项目" align="center">
            <template slot-scope="scp">
              <input
                v-model="scp.row.item"
                :readonly="isReadonly"
                :class="['stepInput', { readText: isReadonly }]"
                @focus="checkNull(scp.row)"
              />
            </template>
          </el-table-column>

          <el-table-column
            prop="marks"
            label="划号"
            align="center"
            width="60"
            v-if="[2, 3, -1].includes(status)"
          >
            <template slot-scope="scp">
              <el-checkbox
                v-model="scp.row.marks"
                v-if="[2].includes(status)"
                :true-label="1"
                :false-label="0"
                size="medium"
              ></el-checkbox>
              <el-checkbox
                v-model="scp.row.marks"
                :true-label="1"
                :false-label="0"
                :disabled="isReadonly"
                size="medium"
                v-if="[3, -1].includes(status)"
              ></el-checkbox>
            </template>
          </el-table-column>

          <el-table-column
            prop="reportTime"
            label="备注"
            align="center"
            width="200"
            v-if="[2, 3, -1].includes(status)"
          >
            <template slot-scope="scp">
              <input
                v-model="scp.row.remarks"
                class="stepInput"
                v-if="[2].includes(status)"
              />
              <input
                v-model="scp.row.remarks"
                v-if="[3, -1].includes(status)"
                :readonly="isReadonly"
                :class="['stepInput', { readText: isReadonly }]"
              />
            </template>
          </el-table-column>

          <el-table-column
            prop="operation"
            label="操作"
            width="180"
            align="center"
            v-if="!isReadonly"
          >
            <template slot-scope="scope">
              <i
                class="el-icon-delete"
                @click="deleteStep(scope.row.rowNum)"
              ></i>
              <i
                class="el-icon-caret-top"
                @click="moveUp(scope.row.rowNum)"
              ></i>
              <i
                class="el-icon-caret-bottom"
                @click="moveDown(scope.row.rowNum)"
              ></i>
              <el-dropdown  @command="handleCommand" @visible-change="vChange(scope.row)">
                <span class="el-dropdown-link">
                  <i class="el-icon-plus"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="up">上方插入一行</el-dropdown-item>
                  <el-dropdown-item command="down">下方插入一行</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <input
      type="file"
      ref="uploadFile"
      style="display: none"
      @change="autoUploadFile"
    />
  </div>
</template>
<script>
import {
  uploadExcel,
  exportStep,
} from "@/api/twoTicketManagement/operationTicket.js";
export default {
  props: {
    //主表ID
    ticketId: {
      type: String,
      default: "",
    },
    //列表数据
    formListData: {
      type: Array,
      default: () => [],
    },
    //列表是否为只读
    isReadonly: {
      type: Boolean,
      default: false,
    },
    status: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      labelPosition: "right",
      tipText: `<i class='el-icon-question' style='font-size: 25px;color: #3f77f4;vertical-align: middle;'></i>
                    步骤常用关键词提示：首关键词（ <span style='color:red'>在、拆除、合上、拉开</span> ）；
                    其他术语名词（ <span style='color:red'>接地刀闸、地刀、接地线</span> ）`,
      rules: {
        //operationStep: [{ required: true }],
      },
      listConfig: {
        listData: [],
      },
      curRow:null,
    };
  },
  methods: {
    //设置头部样式
    headerCellStyle() {
      return {
        background: "#fafafa",
        color: "#333333",
      };
    },
    //设置td样式
    tableCellStyle() {
      return {
        "border-bottom": "1px solid #ebebeb",
        padding: "5px 0!important",
      };
    },
    //增加一行
    addRow() {
      const len = this.listConfig.listData.length;
      this.listConfig.listData.push({ rowNum: len + 1, item: "" });
    },
    //随意插入行
    handleCommand(type){
      const {rowNum} =this.curRow
      type==='up' && this.listConfig.listData.splice(rowNum-1,0,{ rowNum, item: "" });
      type==='down' && this.listConfig.listData.splice(rowNum,0,{ rowNum: rowNum + 1, item: "" });
      //重新排序
      this.listConfig.listData.filter((item, index) => (item.rowNum = index + 1));
    },
    vChange(row){
      this.curRow = row
    },
    //下载导入模板
    downloadModel() {
      this.$utils.downloadFile(
        null,
        null,
        "eam-service-ticket/operation/downExcelDetStepdetTemplate?type=1"
      );
    },
    //导出
    async derive() {
      const arr = this.listConfig.listData.map((obj) => {
        return { item: obj.item };
      });
      if (this.listConfig.listData.length !== 0) {
        const blob = await exportStep(arr);
        let a = document.createElement("a");
        document.body.appendChild(a);
        a.href = window.URL.createObjectURL(new Blob([blob]));
        a.download = "操作步骤.xls";
        a.click();
        document.body.removeChild(a);
      }
    },
    //导入数据
    uploadExcel() {
      const fileObj = this.$refs.uploadFile;
      fileObj.click();
    },
    //自动上传附件并获取回传的数据
    autoUploadFile() {
      const fileObj = this.$refs.uploadFile.files[0];
      const formData = new FormData();
      formData.append("file", fileObj);
      formData.append("type", 1);

      //上传并接收回传的数据
      uploadExcel(formData).then((res) => {
        res.data.forEach((rowData) => {
          rowData.errorMsg &&
            this.$message({
              showClose: true,
              type: "error",
              message: `导入失败：第${rowData.rowNum}行，${rowData.errorMsg}`,
            });
        });
        //合并原有和导入的，并排序
        const orgin = this.listConfig.listData.length===1?(this.listConfig.listData[0].item==="" ? [] :this.listConfig.listData):this.listConfig.listData
        const resArr = [...orgin, ...res.data].filter(
          (item, index) => (item.rowNum = index + 1)
        );
        this.$set(this.listConfig, "listData", resArr);
      });
    },
    //从excel中粘贴
    pasteFromExcel() {
      //localhost或者https才能执行
      navigator.clipboard.readText().then((res) => {
        //分解成数组
        const textArr = res.split("\r\n");
        //删除最后一个空元素
        if (textArr.length > 0 && textArr[textArr.length - 1] === "") {
          textArr.splice(textArr.length - 1, 1);
        }
        //获取序号排到几
        let len = this.listConfig.listData.length;
        textArr.forEach((text) => {
          //excel表格中如果有换行会多“”，需清掉
          text = text.replace(/"/g, "");
          this.listConfig.listData.push({ rowNum: ++len, item: text });
        });
      });
    },
    //删除步骤
    deleteStep(row) {
      //删掉数据
      let data = this.listConfig.listData.filter((item) => item.rowNum != row);
      //重新排序
      let reOrder = data.filter((item, index) => (item.rowNum = index + 1));
      this.$set(this.listConfig, "listData", reOrder);
    },
    //向上移动
    moveUp(row) {
      //交换位置
      if (this.listConfig.listData[row - 2]) {
        //交换位置
        [this.listConfig.listData[row - 1], this.listConfig.listData[row - 2]] =
          [
            this.listConfig.listData[row - 2],
            this.listConfig.listData[row - 1],
          ];

        //重新排序
        let reOrder = this.listConfig.listData.filter(
          (item, index) => (item.rowNum = index + 1)
        );
        this.$set(this.listConfig, "listData", reOrder);
      } else {
        this.$message({
          showClose: true,
          message: "到顶啦！!",
        });
      }
    },
    //向下移动
    moveDown(row) {
      if (this.listConfig.listData[row]) {
        //交换位置
        [this.listConfig.listData[row - 1], this.listConfig.listData[row]] = [
          this.listConfig.listData[row],
          this.listConfig.listData[row - 1],
        ];

        //重新排序
        let reOrder = this.listConfig.listData.filter(
          (item, index) => (item.rowNum = index + 1)
        );
        this.$set(this.listConfig, "listData", reOrder);
      } else {
        this.$message({
          showClose: true,
          message: "到底啦！!",
        });
      }
    },
    //检查上一步骤是否为空，不允许填入内容
    checkNull(rowData) {
      let flag = true;
      let rowNum = 0;
      this.listConfig.listData.filter((obj) => {
        if (obj.rowNum === rowData.rowNum) {
          if (!flag) {
            this.$message({
              showClose: true,
              type: "error",
              message: `请先填写第${rowNum}行步骤`,
            });
          }
          return;
        }
        if (obj.item.trim() === "") {
          rowNum = obj.rowNum;
          flag = false;
        }
      });
    },
    //设置头部标*
    starAdd(obj) {
      if (obj.columnIndex === 1) {
        return "star";
      }
    },
    //自由插入某一行
    selectAdd() {},
  },
  watch: {
    formListData: {
      handler(val) {
        //排序
        const deepCopy = JSON.parse(JSON.stringify(val));
        deepCopy.sort((a, b) => {
          let val1 = parseInt(a.rowNum);
          let val2 = parseInt(b.rowNum);
          if (val1 < val2) {
            return -1;
          } else if (val1 > val2) {
            return 1;
          } else {
            return 0;
          }
        });
        this.listConfig.listData = deepCopy;
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>
<style lang="less" scoped>
.el-icon-delete,
.el-icon-caret-top,
.el-icon-caret-bottom,
.el-icon-plus {
  font-size: 20px;
  color: #2c77f4;
  cursor: pointer;
}
.stepInput {
  padding: 8px 10px;
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 2px;
  color: #606266;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}
.stepInput:focus {
  border: 1px solid #409eff;
}
.readText:focus,
.readText {
  border: 0;
  background-color: transparent;
}
/deep/table th.star .cell::before {
  content: " * ";
  color: red;
}
</style>